<template>
  <div class="calendar">
    <div class="calendar-box" v-loading="loading">
      <FullCalendar :options="calendarOptions" ref="fullCalendar" />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '会议预约' : '会议详情'" width="600"
      :before-close="handleClose">
      <div v-show="dialogType === 'add'">
        <el-form :model="form" ref="ruleFormRef" label-width="auto" :rules="rules" label-position="top"
          style="max-width: 600px">
          <el-form-item label="操作类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择">
              <el-option label="创建新的会议" value="1" />
              <el-option label="加入已存在的会议" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="会议名称" v-show="form.type == '1'" prop="meetingName">
            <el-input v-model="form.meetingName" />
          </el-form-item>
          <el-form-item label="会议列表" v-show="form.type == '2'" prop="meetingId">
            <el-select v-model="form.meetingId" placeholder="请选择" clearable filterable>
              <el-option v-for="item in userMeetingArr" :key="item.meetingId" :label="item.meetingName"
                :value="item.meetingId" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <div v-show="dialogType === 'detail'">
        <el-table :data="tableData" style="width: 100%" scrollbar-always-on max-height="250" v-loading="tableLoading">
          <el-table-column prop="username" align="center" label="用户" />
          <el-table-column prop="email" align="center" label="邮箱" />
          <el-table-column prop="telephone" align="center" label="电话" />
          <el-table-column fixed="right" align="center" label="操作" width="120">
            <template #default="scope">
              <el-popconfirm class="box-item" title="是否退出该会议？" placement="top-end" width="180"
                @confirm="handleDelete(scope.row)">
                <template #reference>
                  <!-- v-if="scope.row.uuid == userInfo.uuid" -->
                  <el-button link type="danger" size="small">退出</el-button>
                </template>
              </el-popconfirm>
              <el-popconfirm class="box-item" title="是否解散该会议？" placement="top-end" width="180">
                <template #reference>
                  <el-button link type="danger" size="small">解散</el-button>
                </template>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer" v-show="dialogType === 'add'">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="btnLoading" @click="submitForm(ruleFormRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick, ref, reactive } from 'vue'
import { useRouter } from "vue-router";
import { formatDateToYMD } from '@/utils/index'

import FullCalendar from '@fullcalendar/vue3'
// 检测dateClick操作、 可选操作以及 事件拖放和调整大小时需要。
import interactionPlugin from '@fullcalendar/interaction';
// 提供月度和每日网格视图 
import dayGridPlugin from '@fullcalendar/daygrid'; // for dayGridMonth v

import { useCalendarStore } from "@/store/calendar.ts";

import { ElMessage, type FormInstance, type FormRules } from "element-plus";

interface RuleForm {
  meetingName: string
  type: string
  meetingId: string
}

const router = useRouter();
const calendarStore = useCalendarStore();
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');

// 弹窗
let dialogVisible = ref(false)
// 类型
let dialogType = ref('add')
// 选中的时间
let selectTime = ref<string>('')
// 
let tableLoading = ref(false)
let tableData = ref([])
// 会议名称查询列表
let userMeetingArr = ref([])
// 选择的日期
let selectDate = ref<string[]>([])
// 提交 loading
let btnLoading = ref(false)


const ruleFormRef = ref<FormInstance>()

const form = reactive({
  meetingName: '',
  type: '1',
  meetingId: '',
})

let fullCalendar = ref(null)
let eventsList = ref([
  {
    id: 'event1',
    title: '团队会议',
    start: new Date(),
    end: new Date(new Date().setHours(new Date().getHours() + 2)),
    color: '#3498db',
    currentUser: 1, // 当前用户是否预约 (1=是, 0=否)
    num: 5          // 所有用户预约总数
  },
  {
    id: 'event1',
    title: '团队会议',
    start: new Date(),
    end: new Date(new Date().setHours(new Date().getHours() + 2)),
    color: '#3498db',
    currentUser: 1, // 当前用户是否预约 (1=是, 0=否)
    num: 5          // 所有用户预约总数
  },
  {
    id: 'event1',
    title: '团队会议',
    start: new Date(),
    end: new Date(new Date().setHours(new Date().getHours() + 2)),
    color: '#3498db',
    currentUser: 1, // 当前用户是否预约 (1=是, 0=否)
    num: 5          // 所有用户预约总数
  },
  {
    id: 'event1',
    title: '团队会议',
    start: new Date(),
    end: new Date(new Date().setHours(new Date().getHours() + 2)),
    color: '#3498db',
    currentUser: 1, // 当前用户是否预约 (1=是, 0=否)
    num: 5          // 所有用户预约总数
  },
  {
    id: 'event2',
    title: '项目评审',
    start: new Date(new Date().setDate(new Date().getDate() + 1)),
    end: new Date(new Date().setDate(new Date().getDate() + 1.5)),
    color: '#2ecc71',
    currentUser: 0,
    num: 3
  },
])
let loading = ref(false)
const rangeStart = ref(null);
const rangeEnd = ref(null);
const currentView = ref('dayGridMonth');


const handleEventClick = (info) => {
  dialogType.value = 'detail'

  tableLoading.value = true
  dialogVisible.value = true
  tableData.value = []

  // 当前选中的时间
  selectTime.value = formatDateToYMD(info?.event?.startStr || info?.event?.endStr)

  // formatDateToYMD()
  // showDateDetail
  // if (confirm(`删除 "${info.event.title}" 事件？`)) {
  //   info.event.remove()
  // }


  new Promise((resolve, reject) => {
    setTimeout(() => {
      tableLoading.value = false
      resolve(true)
    }, 2000)
  })


  // let result = calendarStore.showDateDetail({
  //   meetingDates: [formatDateToYMD(info?.event?.startStr || info?.event?.endStr)]
  // })

  // mock data for testing, do not assign to result if result is a Promise
  const mockData = [
    {
      "id": null,
      "uuid": "123e4567-e89b-12d3-a456-426614174001", //这个字段给前端使用的，不需要展示
      "username": "Bob", //用户
      "password": null, //不需要展示
      "email": "bob@example.com", //用户邮箱
      "telephone": "987654321", //电话
      "isDelete": 0, //不需要展示
      "createTime": null, //不需要展示
      "updateTime": null //不需要展示
    },
    {
      "id": null,
      "uuid": "123e4567-e89b-12d3-a456-426614174002", //这个字段给前端使用的，不需要展示
      "username": "Charlie", //用户
      "password": null, //不需要展示
      "email": "charlie@example.com", //用户邮箱
      "telephone": "112233445", //电话
      "isDelete": 0, //不需要展示
      "createTime": null, //不需要展示
      "updateTime": null //不需要展示
    },
    {
      "id": null,
      "uuid": "123e4567-e89b-12d3-a456-426614174002", //这个字段给前端使用的，不需要展示
      "username": "Charlie", //用户
      "password": null, //不需要展示
      "email": "charlie@example.com", //用户邮箱
      "telephone": "112233445", //电话
      "isDelete": 0, //不需要展示
      "createTime": null, //不需要展示
      "updateTime": null //不需要展示
    }, {
      "id": null,
      "uuid": "123e4567-e89b-12d3-a456-426614174002", //这个字段给前端使用的，不需要展示
      "username": "Charlie", //用户
      "password": null, //不需要展示
      "email": "charlie@example.com", //用户邮箱
      "telephone": "112233445", //电话
      "isDelete": 0, //不需要展示
      "createTime": null, //不需要展示
      "updateTime": null //不需要展示
    }, {
      "id": null,
      "uuid": "123e4567-e89b-12d3-a456-426614174002", //这个字段给前端使用的，不需要展示
      "username": "Charlie", //用户
      "password": null, //不需要展示
      "email": "charlie@example.com", //用户邮箱
      "telephone": "112233445", //电话
      "isDelete": 0, //不需要展示
      "createTime": null, //不需要展示
      "updateTime": null //不需要展示
    }, {
      "id": null,
      "uuid": "123e4567-e89b-12d3-a456-426614174002", //这个字段给前端使用的，不需要展示
      "username": "Charlie", //用户
      "password": null, //不需要展示
      "email": "charlie@example.com", //用户邮箱
      "telephone": "112233445", //电话
      "isDelete": 0, //不需要展示
      "createTime": null, //不需要展示
      "updateTime": null //不需要展示
    },
  ]

  tableData.value = mockData
}

const handleDelete = (row) => {
  try {
    console.log('row', row);

    let result = calendarStore.cancelBook({
      userUuid: userInfo.uuid,
      meetingDates: [selectTime.value],
    })
  } catch (error) {
    console.log('error', error);
  }
}
let calendarOptions = ref({
  timeZone: 'UTC',
  plugins: [dayGridPlugin, interactionPlugin],
  initialView: 'dayGridMonth', // 初始视图
  locale: 'zh-cn', // 语言设置

  // 控制折叠的核心配置
  dayMaxEventRows: 2, // 启用折叠功能

  // 标题工具栏
  headerToolbar: {
    left: 'prevYear,prev,next,nextYear today',
    center: 'title',
    right: 'dayGridMonth,dayGridWeek,dayGridDay',
  },
  customButtons: {
    prevYear: {
      text: '<<',
      click: () => handleToolbarAction('prevYear')
    },
    prev: {
      text: '<',
      click: () => handleToolbarAction('prev')
    },
    next: {
      text: '>',
      click: () => handleToolbarAction('next')
    },
    nextYear: {
      text: '>>',
      click: () => handleToolbarAction('nextYear')
    },
    today: {
      text: '今天',
      click: () => handleToolbarAction('today')
    }
  },
  // 按钮文本
  buttonText: {
    today: '今天',
    month: '月',
    week: '周',
    day: '日',
  },
  // 是否允许用户选择日历上的日期范围。
  selectable: true,
  events: eventsList.value,
  // 自定义事件内容显示
  eventContent: function (arg) {
    // 创建包含自定义字段的DOM元素
    const container = document.createElement('div');
    container.style.padding = '5px';
    container.style.fontSize = '0.9em';

    // 标题
    const title = document.createElement('div');
    title.innerText = arg.event.title;
    title.style.fontWeight = 'bold';
    title.style.marginBottom = '3px';

    // 当前用户状态
    const userStatus = document.createElement('div');
    userStatus.innerText = `您已预约: ${arg.event.extendedProps.currentUser ? '是' : '否'}`;
    userStatus.style.color = arg.event.extendedProps.currentUser ? '#27ae60' : '#e74c3c';
    userStatus.style.fontSize = '0.85em';
    userStatus.style.marginBottom = '3px';

    // 预约总数
    const total = document.createElement('div');
    total.innerText = `总预约数: ${arg.event.extendedProps.num || ''}`;
    total.style.fontSize = '0.85em';
    total.style.marginBottom = '3px';

    container.appendChild(title);
    container.appendChild(userStatus);
    container.appendChild(total);

    return { domNodes: [container] };
  },
  eventClick: handleEventClick,
  select: function (info) {
    dialogType.value = 'add'

    selectDate.value = [
      formatDateToYMD(info.startStr),
      formatDateToYMD(info.endStr)
    ]

    dialogVisible.value = true
  },
})

// 工具栏按钮点击处理
const handleToolbarAction = (action) => {
  if (loading.value) return
  console.log(`点击了工具栏按钮: ${action}`);

  // 获取日历API
  const calendarApi = fullCalendar.value.getApi();

  // 手动触发原生导航操作
  switch (action) {
    case 'prevYear':
      calendarApi.prevYear();
      break;
    case 'prev':
      calendarApi.prev();
      break;
    case 'next':
      calendarApi.next();
      break;
    case 'nextYear':
      calendarApi.nextYear();
      break;
    case 'today':
      calendarApi.today();
      break;
  }

  // 更新日期范围
  updateDateRange(calendarApi.view);
};

// 更新日期范围
const updateDateRange = async (view) => {
  rangeStart.value = formatDateToYMD(view.activeStart.toISOString());
  rangeEnd.value = formatDateToYMD(view.activeEnd.toISOString())
  currentView.value = view.type;

  console.log('rangeStart.value', rangeStart.value);
  console.log('rangeEnd.value', rangeEnd.value);

  await getDateData()
};

// 获取日期数据
const getDateData = async () => {
  try {
    loading.value = true
    const { data } = await calendarStore.searchBook({
      userUuid: userInfo.uuid,
      startDate: rangeStart.value,
      endDate: rangeEnd.value
    })
    console.log('data', data);

    addNewEvent(data)
  } catch (error) {
    console.error('Error in getDateData:', error);
  } finally {
    loading.value = false
  }
}





// 添加新事件
const addNewEvent = (data) => {
  const calendarApi = fullCalendar.value.getApi();
  data = data.filter(item => Number(item.num) > 0)

  calendarApi.addEventSource(data);
  eventsList.value = data
};

// 删除所有事件
const clearEvents = () => {
  const calendarApi = fullCalendar.value.getApi();
  calendarApi.getEvents().forEach(event => event.remove());
  eventsList.value = [];
  console.log('已清除所有事件');
};



const rules = reactive<FormRules<RuleForm>>({
  meetingName: [
    { required: true, message: '请输入', trigger: 'blur' },
    { min: 1, max: 40, message: '长度应为1到40', trigger: 'blur' },
  ],
  type: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
  meetingId: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],

})
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  if (btnLoading.value) return
  btnLoading.value = true
  try {
    await formEl.validate(async (valid, fields) => {
      console.log('valid', valid);
      if (valid) {
        if (userInfo?.uuid) {
          const result = await calendarStore.book({
            "userUuid": userInfo.uuid,
            "meetingName": form.meetingName,
            "meetingDates": selectDate.value,
          })

          console.log('result', result);
          ElMessage.success('添加成功')

          handleClose()

          clearEvents()

          updateDateRange(fullCalendar.value.getApi().view)
        } else {
          ElMessage.error('请先登录')
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  } catch (error) {

  } finally {
    btnLoading.value = false
  }
}
// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false

  // 重置数据
  ruleFormRef.value && ruleFormRef.value?.resetFields()
}



// 引入组件
const main = async () => {
  try {
    // calendarStore.searchBook()

    const result = await calendarStore.selectmettingName()
    console.log('result', result);
    userMeetingArr.value = result?.data || []


    nextTick(() => {
      updateDateRange(fullCalendar.value.getApi().view)
    })
  } catch (error) {
    console.error('Error in main:', error);
  } finally {
    // 这里可以添加一些清理或最终操作
  }
}

main()

</script>

<style lang="scss" scoped>
.calendar {
  .calendar-box {
    box-sizing: border-box;
    width: 100%;
    max-width: 1280px;

    max-height: 800px;

    margin: 0 auto;
    padding: 20px;
  }

  :deep(.fc) {}


}
</style>
